package com.mogujie.tt.imservice.manager;

import android.app.Application;
import android.util.Log;
import android.widget.Toast;

import com.google.protobuf.CodedInputStream;
import com.mogujie.tt.DB.DBInterface;
import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.app.IMApplication;
import com.mogujie.tt.config.NewFriendsConstant;
import com.mogujie.tt.imservice.callback.Packetlistener;
import com.mogujie.tt.imservice.event.NewFriendsEvent;
import com.mogujie.tt.imservice.event.UserInfoEvent;
import com.mogujie.tt.protobuf.IMBaseDefine;
import com.mogujie.tt.protobuf.IMBuddy;
import com.mogujie.tt.protobuf.helper.ProtoBuf2JavaBean;
import com.mogujie.tt.ui.adapter.NewFriendsAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by user on 2015/10/21.
 */
public class IMNewFriendsManager extends IMManager {

    // 单例
    private static IMNewFriendsManager inst = new IMNewFriendsManager();
    public static IMNewFriendsManager instance() {
        return inst;
    }
    private IMSocketManager imSocketManager = IMSocketManager.instance();
    private DBInterface dbInterface = DBInterface.instance();

    private Map<Integer,UserEntity> userFindMap = new ConcurrentHashMap<>();//查看搜索到多少用户
    private Map<Integer,UserEntity> addYouFriendUserMap = new ConcurrentHashMap<>();//想添加你为好友的用户



    @Override
    public void doOnStart() {

    }

    @Override
    public void reset() {

    }
    /**
     * @param event
     */
    public  synchronized void triggerEvent(NewFriendsEvent event) {

        EventBus.getDefault().postSticky(event);
    }
    /**
     * @param event
     */
    public void triggerEvent(UserInfoEvent event) {
        EventBus.getDefault().postSticky(event);
    }

    /** 查找要添加的用户相关协议**/
    /**
     * 查找用户请求
     * @param findUserName
     */
    public void reqGetFindUser(String findUserName) {
   //    Log.v("IMNewFriendsManager", "contact#reqGetFindUser");
        int userId = IMLoginManager.instance().getLoginId();

        IMBuddy.IMFindUserReq imFindUserReq  = IMBuddy.IMFindUserReq.newBuilder()
                .setUserId(userId)
                .setFindInfo(findUserName).build();
        int sid = IMBaseDefine.ServiceID.SID_BUDDY_LIST_VALUE;
        int cid = IMBaseDefine.BuddyListCmdID.CID_BUDDY_LIST_FIND_USER_REQUEST_VALUE;
        imSocketManager.sendRequest(imFindUserReq, sid, cid);
      /*  ,new Packetlistener() {
            @Override
            public void onSuccess(Object response) {
                Log.v("IMNewFriendsManager","reqGetFindUser  onSuccess ");
            }

            @Override
            public void onFaild() {
                Log.v("IMNewFriendsManager","reqGetFindUser  onFaild ");
                //    triggerEvent(new NewFriendsEvent(NewFriendsEvent.Event.FIND_USER_FAIL));
            }

            @Override
            public void onTimeout() {
                Log.v("IMNewFriendsManager","reqGetFindUser  onTimeout ");
            }
        }*/
    }

    public void onRepFindUser(IMBuddy.IMFindUserRsp imFindUserRsp) {
   //     Log.v("IMNewFriendsManager", "contact#onRepFindUser");
        int userId = imFindUserRsp.getUserId();

        int count =  imFindUserRsp.getUserListCount();

        if(count <=0){
      //      Log.v("AddFriendsTwoActivity","searchUser----------0");
            triggerEvent(new NewFriendsEvent(NewFriendsEvent.Event.SEARCH_NO_USER));
            return;
        }

        int loginId = IMLoginManager.instance().getLoginId();
        if(userId != loginId){
            return ;
        }

        List<IMBaseDefine.UserInfo> changeList =  imFindUserRsp.getUserListList();
        ArrayList<UserEntity> needDb = new ArrayList<>();
        for(IMBaseDefine.UserInfo userInfo:changeList){
            UserEntity entity =  ProtoBuf2JavaBean.getUserEntity(userInfo);
            userFindMap.put(entity.getPeerId(),entity);
            needDb.add(entity);
        }
        for ( UserEntity user:needDb){
            NewFriendsConstant.userFind = user;
        /*    Log.v("IMNewFriendsManager","user = "+user.getMainName());
            Log.v("IMNewFriendsManager","user = "+user.getRelation());
            Log.v("IMNewFriendsManager","user = "+user.getRemark());*/
        }

            triggerEvent(new NewFriendsEvent(NewFriendsEvent.Event.SEARCH_USER));

    }
   /**-----------------------------------**/

    /**
     * 添加用户为好友请求
     * @param authInformation
     * @param friendId
     */
    public void reqGetAddFriend(String authInformation,int friendId) {
  //      Log.v("IMNewFriendsManager", "contact#reqGetAddFriend");
        final int userId = IMLoginManager.instance().getLoginId();

        IMBuddy.IMAddFriendReq imAddFriendReq  = IMBuddy.IMAddFriendReq.newBuilder()
                .setUserId(userId)
                .setFriendId(friendId)
                .setRequestInfo(authInformation)
                .build();
        int sid = IMBaseDefine.ServiceID.SID_BUDDY_LIST_VALUE;
        int cid = IMBaseDefine.BuddyListCmdID.CID_BUDDY_LIST_ADD_FRIEND_REQUEST_VALUE;
        imSocketManager.sendRequest(imAddFriendReq, sid, cid,new Packetlistener() {
            @Override
            public void onSuccess(Object response) {
                Log.v("IMNewFriendsManager","reqGetAddFriend  onSuccess ");
            }

            @Override
            public void onFaild() {
                Log.v("IMNewFriendsManager", "reqGetAddFriend  onFaild ");
                NewFriendsConstant.noNetworkAddBuddy =true;

            }

            @Override
            public void onTimeout() {
                Log.v("IMNewFriendsManager","reqGetAddFriend  onTimeout ");
            }
        });
    }


    /**
     * 通知有用户请求添加你
     * @param imAddFriendNotify
     */
    public void onRepAddFriendNotify(IMBuddy.IMAddFriendNotify imAddFriendNotify) {
     //   Log.v("IMNewFriendsManager", "contact#onRepAddFriendNotify");
        int userId = imAddFriendNotify.getUserId();
     //  Log.v("IMNewFriendsManager", "userId = "+userId);

        int friendId = imAddFriendNotify.getFriendId();
     //  Log.v("IMNewFriendsManager", "friendId = "+friendId);

        String  friendAuthCode = imAddFriendNotify.getRequestInfo();
     //   Log.v("IMNewFriendsManager", "friendAuthCode = "+friendAuthCode);

        int count =  imAddFriendNotify.getUserListCount();
      //  Log.v("IMNewFriendsManager", "count = "+count);

        if(count <=0){
            return;
        }

        int loginId = IMLoginManager.instance().getLoginId();
    //    Log.v("IMNewFriendsManager", "loginId = "+loginId);
        if(userId != loginId){
            return ;
        }

        List<IMBaseDefine.UserInfo> changeList =  imAddFriendNotify.getUserListList();
        ArrayList<UserEntity> needDb = new ArrayList<>();
        for(IMBaseDefine.UserInfo userInfo:changeList){
            UserEntity entity =  ProtoBuf2JavaBean.getUserEntity(userInfo);
      //      entity.setRemark(friendAuthCode);//把备注修改成验证添加好友信息
         //   entity.setRelation(2);//把备注改为好友
            addYouFriendUserMap.put(entity.getPeerId(), entity);
        /*    Log.v("IMNewFriendsManager", "user = " + entity.getMainName());
            Log.v("IMNewFriendsManager", "user = " + entity.getRelation());
            Log.v("IMNewFriendsManager", "user = " + entity.getRemark());*/

            needDb.add(entity);
        }
        dbInterface.batchInsertOrUpdateUser(needDb);//更新用户人员数据库
    /*    for(int i =0;i<needDb.size();i++){
            if(needDb.get(i).getRelation() == 3){
       //         Log.v("IMNewFriendsManager", "needDb triggerEvent = " + needDb.get(i).getRelation());
               IMContactManager.instance().addFriendAfter();
                break;
            }
        }*/
        IMContactManager.instance().addFriendAfter();

    /*   List<UserEntity> userlist = dbInterface.loadAllUsers();
        for ( UserEntity user:userlist){
            if(user.getRelation() == 2) {
              Log.v("IMNewFriendsManager", "user = " + user.getMainName());
                Log.v("IMNewFriendsManager", "user = " + user.getRelation());
                Log.v("IMNewFriendsManager", "user = " + user.getRemark());
            }
        }*/

    }

    /**
     * 加载数据库中请求添加你为好友和等待验证添加你为好友
     * @return
     */
    public  ArrayList<UserEntity> loadRequestAddFriendDatabase(){
        ArrayList<UserEntity> requestAddFriend = new ArrayList<UserEntity>();
        List<UserEntity> userlist = dbInterface.loadAllUsers();
        for ( UserEntity user:userlist){
            if(user.getRelation() == 2 ||user.getRelation() == 1) {
                requestAddFriend.add(user);
            }
        }
        return requestAddFriend;
    }


    /**
     * 点击通过好友然后刷新页面
     */
    public void agreeFriendsAdd(int friendId){
        if(NewFriendsConstant.noNetworkAddBuddy == false) {
            List<UserEntity> contactList = dbInterface.loadAllUsers();
            ArrayList<UserEntity> needDb = new ArrayList<>();
            // 没有任何的请求添加好友数据
            if (contactList.size() <= 0) {
                return;
            }
            for (UserEntity user : contactList) {
                if (user.getPeerId() == friendId) {
                    user.setRelation(3);//设置为好友
                    needDb.add(user);
                }
            }
            dbInterface.batchInsertOrUpdateUser(needDb);//添加到用户数据库

            IMContactManager.instance().addFriendAfter();//添加好友后更新
            triggerEvent(new NewFriendsEvent(NewFriendsEvent.Event.REFRESH_REQUEST_FRIENDS));//发送更新数据
        }
        NewFriendsConstant.noNetworkAddBuddy = false;
    }
}
